package com.aries.rpc.spring.starter.service.helper;

import com.aries.dubbo.like.rpc.client.util.TimeOutResponseJob;
import com.aries.dubbo.like.rpc.common.annotations.EnableRpcProvider;
import com.aries.dubbo.like.rpc.server.bootstrap.RpcServerBootStrap;
import com.aries.dubbo.like.rpc.service.util.discover.zk.ZookeeperDiscovery;
import com.aries.rpc.spring.starter.config.RpcConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created with IntelliJ IDEA.
 * Author: aries
 * Date: 2018/8/23
 * Description:
 */
@Configuration
@EnableConfigurationProperties(RpcConfiguration.class)
@Slf4j
@ConditionalOnClass(EnableRpcProvider.class)
public class RpcServerConfiguration {
    @Autowired
    private RpcConfiguration rpcConfiguration;


    /**
     * 启动服务端
     */
    @Bean
    public Integer startServer() {
        int port = Integer.valueOf(rpcConfiguration.getServerPort());
        new Thread(() -> {
            try {
                new RpcServerBootStrap().start(port, rpcConfiguration.getZookeeperAddress(), rpcConfiguration.getBasePath(), Thread.currentThread());
            } catch (Exception e) {
                throw new RuntimeException("rpc server start failed!", e);
            }

        }, "dubbo-style-rpc-thread").start();

        ZookeeperDiscovery.pullZkData();
        TimeOutResponseJob.start();
        return 1;
    }
}
